package epoch.game.core.distr.netty;

import epoch.game.core.distr.INodeAcceptor;
import epoch.game.core.distr.Node;
import epoch.game.core.exception.SysException;
import epoch.game.core.netty.Decoder;
import epoch.game.core.netty.Encoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NodeAcceptor implements INodeAcceptor{
	
	Node node;
	
	public NodeAcceptor(Node node) {
		this.node = node;
	}
	
	@Override
	public void accept(){
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup(Math.max(1, Runtime.getRuntime().availableProcessors() / 2));
		try {
			// 启动netty监听
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 10240)
					.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)		//使用内存池
					.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)	//使用内存池
					.childOption(ChannelOption.TCP_NODELAY, true)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline p = ch.pipeline();
							p.addLast(new Decoder(), new Encoder(), new NodeInboundHandler(node));
						}
					});
			//启动
			b.bind(this.node.getPort()).sync().channel();
//			Channel ch = b.bind(this.node.getPort()).sync().channel();
//			ch.closeFuture().sync();
		} catch (Exception e) {
			throw new SysException(e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	@Override
	public void stopAccept() {
		
	}

}
